﻿using System;
using System.Configuration;
using Unis.Framework.ORM.BaseDefiniens.Enums;

namespace Unis.Framework.ORM.Persistence
{
    public class DbQueryTargetRowCountScope : IDisposable
    {
        // Fields
        [ThreadStatic]
        private static int _OldTargetRowCount = TargetRowCount;
        private bool disposed;
        private static string TARGET_ROW_COUNT_CFG = "DBQueryTargetRowCount";
        [ThreadStatic]
        public static int TargetRowCount;

        // Methods
        static DbQueryTargetRowCountScope()
        {
            string str = ConfigurationManager.AppSettings[TARGET_ROW_COUNT_CFG];
            if (!string.IsNullOrEmpty(str))
            {
                TargetRowCount = Convert.ToInt32(str);
            }
            else
            {
                TargetRowCount = 0;
            }
        }

        public DbQueryTargetRowCountScope(int rowCount)
        {
            TargetRowCount = rowCount;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    TargetRowCount = _OldTargetRowCount;
                }
                this.disposed = true;
            }
        }

        ~DbQueryTargetRowCountScope()
        {
            this.Dispose(false);
        }

        public static string GetTargetRowCountSqlFilter(DatabaseType dbaseType)
        {
            if ((TargetRowCount > 0) && (dbaseType == DatabaseType.Oracle))
            {
                return string.Format("ROWNUM <= {0}", TargetRowCount);
            }
            return string.Empty;
        }
    }
}
